from django.conf import settings
from django.http.response import JsonResponse
from django.shortcuts import render

# Create your views here.


# usernames/(?P<username>\w{5,20})/count/
from django_redis import get_redis_connection

from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from itsdangerous import TimedJSONWebSignatureSerializer as TJS

from goods.models import SKU
from goods.serializers import SKUSerializer
from users import serializers
from users.models import User
from users.serializers import UserDetailSerializer, EmailSerializer, AddUserBrowsingHistorySerializer


class UsernameCountView(APIView):
    """判断用户名是否存在"""

    def get(self, request, username):


        # 获取参数
        count = User.objects.filter(username=username).count()
        # 判断参数
        if count:
            # 在函数里面已经封装好了 自动转成json格式的数据
            return Response({'message': '用户名已经存在'})
        return Response({
            "username": username,
            'count': count
        })
        # 返回值处理


# http://api.meiduo.site:8000/mobiles/13794124773/count/
# /mobiles/13794124773/count/
# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """判断手机号码是否存在"""
    def get(self, request, mobile):
        count = User.objects.filter(mobile=mobile).count()
        if  count:
            return Response({'message': '手机号码已存在'})

        return Response({
            'count': count,
            'mobile': mobile
        })


class UserView(CreateAPIView):
    """
    用户注册
    """
    serializer_class = serializers.CreateUserSerializer


class UserDetailView(RetrieveAPIView):
    """
    用户详情, 由于是获取单个数据, 所以用的就是RetrieveAPIView
    """
    serializer_class = UserDetailSerializer
    # 权限认证 只有注册用户 才可以进入个人中心
    permission_classes = [IsAuthenticated]

    def get_object(self):

        return self.request.user


class EmailView(UpdateAPIView):
    """
    保存用户邮箱
    """
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer

    def get_object(self):

        return self.request.user


# url(r'^email/verification/$', views.VerifyEmailView.as_view()),
class VerifyEmailView(APIView):
    """
    邮箱验证
    """
    def get(self, request):
        # 获取参数

        token = request.query_params.get('token')
        # 解密获取到的数据
        tjs = TJS(settings.SECRET_KEY, 300)
        try:
            data = tjs.loads(token)
        except Exception:
            return Response({
                'message': 'token的值错误'
            })
        # 校验数据
        if not token:
            return Response({
                'message': 'token的值已经过期'
            })
        try:
            user = User.objects.get(id=data['user_id'], email=data['email'])

        except Exception:
            return Response({
                'message': '用户不存在'
            })

        # 保存数据
        user.email_active = True
        user.save()

        # 返回数据
        return Response({'message1': 'ok'})


class UserBrowsingHistoryView(CreateAPIView):
    """
    用户浏览历史记录
    """
    serializer_class = AddUserBrowsingHistorySerializer
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user

        # 建立连接
        conn = get_redis_connection('history')

        # 数据获取
        sku_id_list = conn.lrange('history_%s' % user.id, 0, 5)

        # [1,2,3]
        print(sku_id_list)
        # 查询数据
        sku_list = []
        for sku_id in sku_id_list:
            # 这边还是要rty 不然报错会出错
            try:
                sku = SKU.objects.get(id=sku_id.decode())
                sku_list.append(sku)
            except Exception as e:
                sku = 1

        # 序列化返回
        ser = SKUSerializer(sku_list, many=True)

        return Response(ser.data)
